﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Contrast
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DMLA200 dml = new DMLA200();
        private void Form1_Load(object sender, EventArgs e)
        {
         
           this.txtscann_ip.Text= XML.read("scanner_ip", "p.xml");
           this.txtscann_prot.Text = XML.read("scanner_port", "p.xml");
            string ni = XML.read("alert_prot", "p.xml");
            cboAlert_prot.SelectedItem = ni;
           this.txtBaudrate.Text = XML.read("Baudrate", "p.xml");
            txtalertTime.Text = XML.read("Alter_time", "p.xml");
            SqlDbHelper.OpenConn();
            bindcboHospital("");
            dml.finPrint += Dml_finPrint;

        }
        //读取到视觉的数据
        private void Dml_finPrint(string Mes)
        {
            Thread th = new Thread(new ParameterizedThreadStart(AnscDml_finPrint));
            th.Start(Mes);
        }

        private void AnscDml_finPrint(object Mespar)
        {
            string Mes = Mespar.ToString();
            if (Mes.Contains(","))
            {
                Mes = Mes.Replace("\r\n", "");
                //读取到标签
                string[] list = Mes.Split(new char[1] { ',' });
                if (list[0] != list[1])
                {
                    //标签不相同就报警
                    alert("条码和字符内容不一致！" + list[0] + "   " + list[1]);
                }
                else
                {
                    //插入数据库
                    int count = SqlDbHelper.ExecuteNonQuery("insert into table_codes values (" + HospitalVaule + ",'" + list[0] + "')");
                    if (count == 0)
                    {
                        alert("条码已经存在：" + list[0]);
                        //insetLog("条码已经存在：" + list[0]);
                    }
                    else
                    {
                        this.Invoke(new Action(() =>
                        {
                            this.lblLastText.Text = list[0];

                        }));

                    }
                }

            }
            else
            {
                //直接报警
                alert("视觉没读取到数据");

            }
        }



        //报警的方法
        private void alert(string mes)
        {
            insetLog(mes);
            IOHelp.sendOpen(com, 1);
           
        }

        private void button4_Click(object sender, EventArgs e)
        {
            XML.write("scanner_ip", txtscann_ip.Text, "p.xml");
            XML.write("scanner_port", txtscann_prot.Text, "p.xml");
            XML.write("alert_prot", cboAlert_prot.SelectedItem.ToString(), "p.xml");
            XML.write("Baudrate", txtBaudrate.Text, "p.xml");
            XML.write("Alter_time", txtalertTime.Text, "p.xml");
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 fomr2 = new Form2();
            if (fomr2.ShowDialog() == DialogResult.OK)
            {
                bindcboHospital("");
            }
        }

        private void bindcboHospital(string name)
        {
            //加载医院数据
            DataTable tab = SqlDAL.GetHospitalList(name);
          
                this.cboHospital.DisplayMember = "name";
                this.cboHospital.ValueMember = "id";
                this.cboHospital.DataSource = tab;
           
        }
        private void UIEnabled(bool isEnabled)
        {
            button4.Enabled = isEnabled;
            button1.Enabled = isEnabled;
            button2.Enabled = isEnabled;
           // button3.Enabled = isEnabled;
            txtBaudrate.Enabled= isEnabled;
            txtscann_ip.Enabled= isEnabled;
            txtscann_prot.Enabled= isEnabled;
            cboAlert_prot.Enabled = isEnabled;
            cboHospital.Enabled = isEnabled;
            button7.Enabled = isEnabled;
            button8.Enabled = isEnabled;
            button9.Enabled = isEnabled;
            button10.Enabled = isEnabled;
            this.txtalertTime.Enabled = isEnabled;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (cboHospital.Items.Count > 0 && cboHospital.SelectedIndex != -1)
            {
                HospitalVaule = (int)cboHospital.SelectedValue;
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Multiselect = true;
                fileDialog.Title = "请选择文件";
                fileDialog.Filter = "文本文件(*.txt)|*.txt"; //设置要选择的文件的类型

                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    string file = fileDialog.FileName;//返回文件的完整路径      

                    if (!backgroundWorker1.IsBusy)
                    {
                        UIEnabled(false);
                        insetLog("导入医院数据开始，请等待.....");
                        backgroundWorker1.RunWorkerAsync(file);
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择医院");
            }

        }
        int HospitalVaule = -1;
        string com = "";

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string file = e.Argument.ToString();
            StreamReader sR1 = new StreamReader(file);
            string HospitalStr = sR1.ReadToEnd();
            List<string> list =  HospitalStr.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
            DataTable dt = GetTableSchema();
            foreach (var item in list)
            {
                if (item != "")
                {
                    DataRow row = dt.NewRow();
                    row["hos_id"] = HospitalVaule;
                    row["code_str"] = item;
                    dt.Rows.Add(row);
                }
            }
            SqlDbHelper.InsertTwo(dt);
            
        }

        public static DataTable GetTableSchema()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(
                new DataColumn[] {
        new DataColumn("hos_id",typeof(int)),
        new DataColumn("code_str",typeof(string))});
            return dt;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            button3.Enabled = false;
            if (button3.Text == "启动") {
                if (cboHospital.Items.Count > 0 && cboHospital.SelectedIndex != -1)
                {
                    string isok = dml.Open(txtscann_ip.Text, txtscann_prot.Text);
                    if (isok != "ok")
                    {
                        insetLog("连接视觉相机失败:" + isok);
                        button3.Enabled = true;
                        return;
                    }
                    IOHelp.AlertTime = int.Parse(this.txtalertTime.Text);
                    com = this.cboAlert_prot.SelectedItem.ToString();
                    isok = IOHelp.Open(this.cboAlert_prot.SelectedItem.ToString(), txtBaudrate.Text);
                    if (isok != "ok")
                    {
                        dml.Close();
                        insetLog("连接报警器失败:" + isok);
                        button3.Enabled = true;
                        return;
                    }
                    HospitalVaule = (int)cboHospital.SelectedValue;
                    insetLog("启动软件成功!");
                    UIEnabled(false);
                    button3.Text = "停止";
                }
                else
                {
                    MessageBox.Show("请选择医院信息");
                }
            }
            else
            {
                dml.Close();
                IOHelp.Close();
                insetLog("软件停止!");
                UIEnabled(true);
                button3.Text = "启动";
            }
            button3.Enabled = true;
        }

        private void insetLog(string mes)
        {
            WriteFileCls.InserLog(mes);
            mes = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss：") + mes;
          
            this.Invoke(new Action(() =>
            {
                this.listBox1.Items.Insert(0,mes);
            }));
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            insetLog("导入医院数据成功");
            UIEnabled(true);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            dml.Close();
            IOHelp.Close();
            SqlDbHelper.CloseConn();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            button5.Enabled = false;
            try
            {
                IOHelp.RestAlert(this.cboAlert_prot.SelectedItem.ToString());
                insetLog("重置报警成功！");
            }
            catch(Exception ex)
            {
                insetLog("重置报警失败！"+ ex.Message);
                MessageBox.Show(ex.Message);
            }
            button5.Enabled = true;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            AnscDml_finPrint(this.textBox1.Text);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Form3 passfrom = new Form3();
            if (passfrom.ShowDialog() == DialogResult.OK)
            {
                button7.Enabled = false;

                if (cboHospital.Items.Count > 0 && cboHospital.SelectedIndex != -1)
                {
                    if (MessageBox.Show("确认删除医院数据吗？删除后不可恢复!!", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //+ "delete from table_codes where hos_id=" + selval
                        int selval = (int)cboHospital.SelectedValue;
                        if (!backgroundWorker1.IsBusy)
                        {
                            UIEnabled(false);
                            insetLog("删除医院数据开始，请等待.....");
                            backgroundWorker2.RunWorkerAsync(selval);
                        }

                    }
                }
                else
                {
                    button7.Enabled = true;
                    MessageBox.Show("请先选择医院");
                }
            }
           // button7.Enabled = true;

        }

        private void button8_Click(object sender, EventArgs e)
        {
            bindcboHospital(this.textBox2.Text);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            UIEnabled(false);
            Form3 passfrom = new Form3();
            if (passfrom.ShowDialog() == DialogResult.OK)
            {
                if (MessageBox.Show("确认删全部除医院数据吗？删除后不可恢复!!", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    int selval = (int)cboHospital.SelectedValue;
                    int isok = SqlDbHelper.ExecuteNonQuery("truncate table table_codes");
                    //bindcboHospital("");
                    insetLog("删除全部医院数据成功!");
                }
            }
            UIEnabled(true);
        }

        private void button10_Click(object sender, EventArgs e)
        {

            button10.Enabled = false;
            Form3 passfrom = new Form3();
            if (passfrom.ShowDialog() == DialogResult.OK)
            {
                if (cboHospital.Items.Count > 0 && cboHospital.SelectedIndex != -1)
                {
                    if (MessageBox.Show("确认删除医院吗？删除后不可恢复!!", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //+ "delete from table_codes where hos_id=" + selval
                        int selval = (int)cboHospital.SelectedValue;
                        int isok = SqlDbHelper.ExecuteNonQuery("delete from hospital_info where id=" + selval + ";");
                        if (isok > 0)
                        {
                            //bindcboHospital("");
                            insetLog("删除医院成功!");
                            bindcboHospital("");
                        }
                        else
                        {
                            insetLog("删除医院失败或没有要删除的医院!");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先选择医院");
                }
            }
            button10.Enabled = true;
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            int isok = SqlDbHelper.ExecuteNonQuery("delete from table_codes where hos_id=" +e.Argument + ";");
            e.Result = "0";
            if (isok > 0)
            {
                //bindcboHospital("");
                // insetLog("删除医院数据开始!");
                e.Result = "1";

            }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result.ToString() == "1") { 
            insetLog("删除医院数据成功!");
            }
            else
            {
                insetLog("删除医院数据失败或没有要删除的数据!");

            }
            UIEnabled(true);
        }



        private void 修改删除密码ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            Form4 passfrom = new Form4();
            if (passfrom.ShowDialog() == DialogResult.OK)
            {

            }
        }
    }
}
